package fr.sedoo.metadata.client.ui.widget.field.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import fr.sedoo.commons.client.util.ElementUtil;
import fr.sedoo.metadata.client.ui.widget.field.primitive.ChosenListBoxField;
import fr.sedoo.metadata.shared.domain.MetadataDTO;
import fr.sedoo.metadata.shared.domain.misc.Iso6392LanguageProvider;

public class DataLanguages extends ChosenListBoxField {
	private List<String> languages;

	public DataLanguages(List<String> languages) {
		super();
		this.languages = languages;
		init();
	}

	/**
	 * Build the list box with the editing languages defined in the client
	 * factory
	 */
	private void init() {
		Iterator<String> iterator = languages.iterator();
		while (iterator.hasNext()) {
			String code = iterator.next();
			String label = Iso6392LanguageProvider.getDisplayNameFromCode(code);
			listBox.addItem(label, code);
		}
		listBox.update();
	}

	@Override
	public void display(MetadataDTO metadata) {
		ElementUtil.show(label);
		listBox.setVisible(false);
		label.setText(metadata.getOtherPart().getResourceLanguageLabelsAsString());
	}

	@Override
	public void flush(MetadataDTO metadata) {
		List<String> resourceLanguages = new ArrayList<String>();
		int itemCount = listBox.getItemCount();
		for (int i = 0; i < itemCount; i++) {
			if (listBox.isItemSelected(i)) {
				resourceLanguages.add(listBox.getValue(i));
			}
		}

		metadata.getOtherPart().setResourceLanguages(resourceLanguages);
	}

	@Override
	public void edit(MetadataDTO metadata) {
		ElementUtil.hide(label);
		listBox.setVisible(true);

		List<String> resourceLanguages = metadata.getOtherPart().getResourceLanguages();
		Iterator<String> iterator = resourceLanguages.iterator();
		int itemCount = listBox.getItemCount();
		while (iterator.hasNext()) {
			String key = iterator.next();
			for (int i = 0; i < itemCount; i++) {
				if (listBox.getValue(i).compareToIgnoreCase(key) == 0) {
					listBox.setItemSelected(i, true);
					break;
				}
			}
		}

		listBox.update();

	}

}
